package com.ruoyi.web.dataAccept;


import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.common.CommonController;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 水文气象处理程序
 */
@RequiredArgsConstructor
@Service
@ChannelHandler.Sharable
public class HbDataHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(ChannelInboundHandlerAdapter.class);

    /**
     * 暂存未一次性接收完毕的报文
     */
    private static final CopyOnWriteArrayList<String> messageList = new CopyOnWriteArrayList<>();

    /**
     * 半个
     */
    private volatile String messageHalfKey = null;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接成功：{}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接已断开：{}", ctx.channel().remoteAddress());
        super.channelInactive(ctx);
    }

    /**
     * AIS数据解析
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        clientIP = StringUtils.isNotEmpty(clientIP) ? clientIP : "";
        // final String deviceNo = "192009085027"; // getDevieNoFromIP(clientIP);
        final String deviceNo = getDevieNoFromIP(clientIP);
        String messageBody = (String) msg;
        log.info("接收报文：[" + clientIP + "] :" + messageBody);
        if (StringUtils.isEmpty(messageBody)) {
            log.error("报文异常，数据为空不进行处理");
            return;
        }
        if (messageBody.startsWith("!BEATHEART")) {
            // 心跳请求不处理
            return;
        }

        // 正常报文
        if (messageBody.startsWith("!ABVDM") || messageBody.startsWith("!AIVDM")) {
            String[] messageArr = messageBody.split(",");
            // 消息分几段发完
            int segmentNum = Integer.parseInt(messageArr[1]);
            if (segmentNum == 1) {
                // 报文一次性发完
                // 处理报文
                InputStream inputStream = new ByteArrayInputStream(messageBody.getBytes());

            } else {
                // 报文未一次接收完毕
                // 句号
                int sentenceNo = Integer.parseInt(messageArr[2]);
                if (segmentNum != sentenceNo) {
                    // 未结束时，将半个消息暂存
                    messageList.add(messageBody);
                    // 设置下一个要接收的key
                    synchronized (this) {
                        this.messageHalfKey = segmentNum + ":" + (sentenceNo + 1);
                    }
                } else {
                    // 相等的号，说明消息结束
                    StringBuffer lastMesasge = new StringBuffer();
                    for (String message : messageList) {
                        lastMesasge.append(message).append("\n");
                    }
                    lastMesasge.append(messageBody).append("\n");

                    // 处理报文

                    synchronized (this) {
                        messageList.clear();
                        this.messageHalfKey = null;
                    }
                }

            }
        }
    }

    /**
     * 将IP每个数字格式成3位，拼拉成12位设备号
     *
     * @param IP
     * @return
     */
    private String getDevieNoFromIP(String IP) {
        StringBuffer result = new StringBuffer();
        if (StringUtils.isEmpty(IP)) {
            return null;
        }
        String[] ips = IP.split("\\.");
        if (ips.length < 4) {
            //logger.error("[AIS]## IP {}异常", IP);
            return null;
        }
        for (int i = 0; i < ips.length; i++) {
            String prefix = "";
            for (int j = 0; j < 3 - ips[i].length(); j++) {
                prefix += "0";
            }
            result.append(prefix).append(ips[i]);
        }
        return result.toString();
    }


    /**
     * 验证经纬度是否合法
     *
     * @param longitude
     * @param latitude
     * @return
     */
    private boolean isValidLonLat(Float longitude, Float latitude) {
        if (longitude == null || latitude == null) {
            return false;
        }
//        if (longitude.intValue() != 121 || latitude.intValue() != 38) {
//            return false;
//        }
        return true;
    }

    /**
     * 处理数据入库
     *
     * @param aisMessage
     */
    private void handleAisData(String deviceNo, String aisMessage) {
        log.info("处理消息内容：{}", aisMessage);
        //originMsgMapper.insert(originMsg);

        try {
          /*  if (aisMessage instanceof PositionReportClassAScheduled) {

            } else if (aisMessage instanceof PositionReportClassAAssignedSchedule) {

            } else if (aisMessage instanceof ExtendedClassBEquipmentPositionReport) {

            }*/
        } catch (RuntimeException e) {
            log.error("[AIS]## AIS消息处理异常：{}", e);
        }
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }


}
